import { View, Form, Picker, Input, Button, Table } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { getAppVersionListApi, uploadAppPackageApi, deleteAppPackageApi } from '@/api/handleAppVersion.js'
import './UploadFile.scss'

const UploadFile = () => {
  const [formState, setFormState] = useState({
    version: '',
    fileOwnership: '',
    file: [],
  })
  const [dataSource, setDataSource] = useState([])
  const [fileOwnershipRange] = useState(['yrzj', 'knoTree'])

  useEffect(() => {
    searchHistoryAppVersionList()
  }, [])

  const searchHistoryAppVersionList = async () => {
    let res = await getAppVersionListApi('')
    setDataSource(res?.map((item) => ({
      key: item.id.toString(),
      fileOwnership: item.fileOwnership,
      fileName: item.fileName,
      version: item.version,
      remotePath: item.filePath,
      isAbandon: item.isAbandon ? '是' : '否',
    })))
  }

  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormState(prevState => ({ ...prevState, [name]: value }))
  }

  const onPickerChange = (e) => {
    setFormState(prevState => ({ ...prevState, fileOwnership: fileOwnershipRange[e.detail.value] }))
  }

  const chooseFile = () => {
    Taro.chooseFile({
      type: 'all',
      success(res) {
        setFormState(prevState => ({ ...prevState, file: res.tempFiles }))
      }
    })
  }

  const onSubmit = async () => {
    if (!formState.fileOwnership || !formState.version || formState.file.length === 0) {
      Taro.showToast({ title: '请填写完整信息', icon: 'none' })
      return
    }

    const formData = {
        filePath: formState.file[0].path,
        name: 'file',
        formData: {
            version: formState.version,
            fileOwnership: formState.fileOwnership
        }
    };

    await uploadAppPackageApi(formData).then((res) => {
        if(res){
            console.log('上传成功', res);
            Taro.showToast({title: '上传成功', icon: 'success'})
        }
    }).catch((err) => {
        console.log('上传失败', err);
        Taro.showToast({title: '上传失败', icon: 'none'})
    });
  }

  const onDelete = async (record) => {
    let res = await deleteAppPackageApi({ id: record.key, remotePath: record.remotePath });
    if (res) {
      await searchHistoryAppVersionList()
      Taro.showToast({ title: '删除成功', icon: 'success' })
    } else {
      Taro.showToast({ title: '删除失败', icon: 'none' })
    }
  };

  const columns = [
    { title: '文件归属', dataIndex: 'fileOwnership' },
    { title: '文件名', dataIndex: 'fileName' },
    { title: '版本号', dataIndex: 'version' },
    { title: '远程路径', dataIndex: 'remotePath' },
    { title: '是否废弃', dataIndex: 'isAbandon' },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => (
        <Button onClick={() => onDelete(record)}>Delete</Button>
      ),
    },
  ];

  return (
    <View>
      <Form onSubmit={onSubmit}>
        <Picker mode='selector' range={fileOwnershipRange} onChange={onPickerChange}>
          <View>文件归属: {formState.fileOwnership}</View>
        </Picker>
        <Input name='version' placeholder='版本号' value={formState.version} onInput={handleInputChange} />
        <Button onClick={chooseFile}>选择文件</Button>
        <Button formType='submit' type='primary'>上传</Button>
      </Form>
      <Table columns={columns} dataSource={dataSource} />
    </View>
  )
}

export default UploadFile